//
//  CodeExchange.m
//  ECGDiagnosisCodeExchanger
//
//  Created by jia yu on 2021/11/12.
//

#import "vhECGCodes.h"
#import "CodeItem.h"
vhECGCodes *staticCodeExchanger;

@interface vhECGCodes(){
    NSBundle *myBundle;
}
@end

@implementation vhECGCodes
@synthesize interpretationCodesGroupsArray;
@synthesize currentLanguageCode;

-(void)setCurrentLanguageCode:(NSString *)_currentLanguageCode{
    if (NO == [self isAvailableLangCode:_currentLanguageCode]){
        NSLog(@"%@ is NOT available language code.", _currentLanguageCode);
        return;
    }
    currentLanguageCode = _currentLanguageCode;
    [self reload];
}

-(BOOL)isAvailableLangCode:(NSString *)targetLanguageCode{
    for (NSString *s in [vhECGCodes availableLanguageCodes]){
        if ([[s lowercaseString] isEqualToString:[targetLanguageCode lowercaseString]]){
            return YES;
        }
    }
    return NO;
}

-(void)reload{
    NSString *file = [myBundle pathForResource:[NSString stringWithFormat:@"ecgCode_%@", currentLanguageCode] ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:file];
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (NSString *key in [dict allKeys]){
        CodeGroup *group = [[CodeGroup alloc] initWithName:key items:[dict valueForKey:key]];
        [tempArray addObject:group];
    }
    interpretationCodesGroupsArray = [tempArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        CodeGroup *item1 = (CodeGroup *)obj1;
        CodeGroup *item2 = (CodeGroup *)obj2;
        return [item1.key compare:item2.key];
    }];
    return;
}

-(id)init{
    self = [super init];
    if (self){
        NSString *codeBundle_Path = [self code_pathForResource:@"CodeResources" type:@"bundle" bundleName:@"vhECGCodes"];
        if (nil == codeBundle_Path){
            NSLog(@"frameworkBundle NOT FOUND!");
            return nil;
        }
        myBundle = [[NSBundle alloc] initWithPath:codeBundle_Path];
        if (nil == myBundle){
            NSLog(@"CodeResources.bundle NOT FOUND!" );
            return nil;
        }
        
        currentLanguageCode = [[[NSLocale preferredLanguages] objectAtIndex:0] lowercaseString];
        if ([[@"zh_Hant_HK" lowercaseString] isEqualToString:currentLanguageCode]
            || [[@"zh-Hant-HK" lowercaseString] isEqualToString:currentLanguageCode]){
            //繁体中文 香港
            currentLanguageCode = @"hk";
        }else if ([[@"zh-Hant-TW" lowercaseString] isEqualToString:currentLanguageCode]
                  || [[@"zh_Hant_TW" lowercaseString] isEqualToString:currentLanguageCode]){
            //繁体中文 台湾
            currentLanguageCode = @"hk";
        }else if ([[@"zh_Hant_MO" lowercaseString] isEqualToString:currentLanguageCode]
                  || [[@"zh-Hant-MO" lowercaseString] isEqualToString:currentLanguageCode]){
            //繁体澳门
            currentLanguageCode = @"hk";
        }else if ([[@"zh-Hant-CN" lowercaseString] isEqualToString:currentLanguageCode]
                  || [[@"zh_Hant_CN" lowercaseString] isEqualToString:currentLanguageCode]){
            //繁体中文
            currentLanguageCode = @"hk";
        }else if ([[@"zh-Hans-CN" lowercaseString] isEqualToString:currentLanguageCode]
                  || [[@"zh_Hans_CN" lowercaseString] isEqualToString:currentLanguageCode]){
            //简体中文
            currentLanguageCode = @"zh";
        }else if ([@"zh" isEqualToString:[currentLanguageCode substringToIndex:2]]){
            //其他简体中文
            currentLanguageCode = @"zh";
        }else{
            //@"en-CN"
            //en-GB 英文 英国
//            NSLog(@"Other");
            currentLanguageCode = [currentLanguageCode substringToIndex:2];
        }

//        NSLog(@"Current language code is %@", currentLanguageCode);
        if (NO == [self isAvailableLangCode:currentLanguageCode]){
            currentLanguageCode = @"en";
        }
        [self reload];
    }
    return self;
}

+(NSArray <NSString *>*)availableLanguageCodes{
    return @[@"de",@"en",@"es",@"fr",@"hk",@"it",@"ja",@"tr",@"zh"];
}

+(vhECGCodes *)shareCodeExchange{
    if (nil == staticCodeExchanger){
        staticCodeExchanger = [[vhECGCodes alloc] init];
    }
    return staticCodeExchanger;
}

-(NSString *)stringFromCode:(NSInteger)code{
    for (CodeGroup *group in interpretationCodesGroupsArray){
        for (CodeItem *item in group.items){
            if (item.interpretationCode == code){
                return item.itemString;
            }
        }
    }
    return @"";
}

-(NSArray <NSString *>*)interpretationCodesToStringsArray:(NSArray *)requestCodesArray{
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    for (NSString *request in requestCodesArray){
        NSString *str = [self stringFromCode:[request integerValue]];
        [resultArray addObject:str];
    }
    return resultArray;
}

-(NSString *)withInterpretationCodes:(NSArray *)requestCodesArray{
    NSArray *strArray = [self interpretationCodesToStringsArray:requestCodesArray];
    NSMutableString *result = [[NSMutableString alloc] init];
    for (NSString *str in strArray){
        if (result.length > 0){
            [result appendString:@" "];
        }
        [result appendString:str];
        [result appendString:@"."];
    }
    if (result.length > 0){
        [result appendString:@" "];
    }
    return result;
}

-(NSString * _Nullable )stringForCode:(NSInteger)interpretationCode{
    return [self stringFromCode:interpretationCode];
}

-(NSString *)withInterpretationCodes:(NSArray *)requestCodesArray withMinnesotaCodes:(NSArray *)minnesotaCodes{
    NSArray *strArray = [self interpretationCodesToStringsArray:requestCodesArray];
    
    NSMutableString *result = [[NSMutableString alloc] init];
    for (int i=0;i<strArray.count;i++ ){
        NSString *str = [strArray objectAtIndex:i];
        if (result.length > 0){
            [result appendString:@" "];
        }
        [result appendString:str];
        [result appendString:@"."];
    }
    for (NSString *code in minnesotaCodes){
        if (result.length > 0){
            [result appendString:@" "];
        }
        [result appendString:code];
        [result appendString:@"."];
    }
    return result;
}

// 找到某资源path
//@public
- (NSString*)code_pathForResource:(NSString*)resourceName type:(NSString*)type bundleName:(nullable NSString*)bundleName {
    NSBundle *bundle = [self code_bundleWithName:bundleName];
    return [bundle pathForResource:resourceName ofType:type];
}

/// 根据bundle获取指定bundle对象
- (NSBundle*)code_bundleWithName:(nullable NSString*)bundleName {
    if ([self code_bundlePathWithPodName:bundleName] == nil) return [NSBundle mainBundle];
    return [NSBundle bundleWithPath:[self code_bundlePathWithPodName:bundleName]];
}

/// 根据podName找到bundlePath
//@private
- (nullable NSString*)code_bundlePathWithPodName:(nullable NSString*)podName {
    if(!podName || !podName.length) return nil;
    for (NSBundle* bundle in NSBundle.allBundles) {
        NSString *bundlePath = [bundle pathForResource:podName ofType:@"bundle"];
        if(bundlePath && bundlePath.length>0) return bundlePath;
    }
    for (NSBundle* bundle in [NSBundle allFrameworks]) {
        NSString *bundlePath = [bundle pathForResource:podName ofType:@"bundle"];
        if(bundlePath && bundlePath.length>0) return bundlePath;
    }
    return nil;
}
@end
